﻿using System.Linq;
using System.Web.Mvc;

using NJ.Common.Ioc;
using NJ.Common.Log;
using NJ.Common.Network;
using NJ.Common.Web;
using NJ.Dto.Log;
using NJ.Service.Log;

namespace NJ.Web.Filter
{
    /// <summary>
    /// 异常监控
    /// </summary>
    public class ExceptionFilterAttribute : HandleErrorAttribute
    {
        private ILogger logger = AutoFacConfig.Resolve<ILogger>();
        private ILogService logService = AutoFacConfig.Resolve<ILogService>();

        public override void OnException(ExceptionContext filterContext)
        {
            var stackTrace = filterContext.Exception.StackTrace;
            var message = filterContext.Exception.Message;
            var method = filterContext.HttpContext.Request.HttpMethod;
            var requestUrl = filterContext.HttpContext.Request.Url.AbsoluteUri;

            var client = filterContext.HttpContext.Request.UserAgent;
            var query = filterContext.HttpContext.Request.Url.Query;
            var form = string.Join("&", filterContext.HttpContext.Request.Form.AllKeys.Select(t => $"{t}={filterContext.HttpContext.Request.Form[t]}"));

            logService.AddErrorLogAsync(new ErrorLogDto
            {
                RequestUrl = requestUrl,
                Message = $"异常描述：{message}\r\n 堆栈信息：{stackTrace}",
                Method = method,
                Query = query,
                Form = form,
                ClientIP = Net.Ip,
                ClientName = client
            });
            logger.Error($"\r\n异常描述：{message}\r\n堆栈信息：{stackTrace}");

            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.StatusCode = 500;
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                //ajax异常处理
                filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
                filterContext.Result = new JsonNetResult { Data = new HttpResult { msg = message, status = ResultState.error }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }
            else
            {
                filterContext.HttpContext.Response.Redirect("~/500.html");
            }
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;//禁用IIS自定义错误
        }
    }
}